﻿using System.Xml.Linq;

namespace EasyXaf.DynamicForm.Models;

public class Tabs : FormItem
{
    public int ActiveTabIndex { get; set; }

    public List<TabPanel> TabPanels { get; }

    public Tabs(Form form, Element parent)
        : base(form, parent)
    {
        TabPanels = [];
    }

    public override void WriteXml(XElement element)
    {
        base.WriteXml(element);

        SetXmlAttributeValue(element, "active-tab-index", ActiveTabIndex);

        foreach (var tabPanel in TabPanels)
        {
            var tabPanelElement = tabPanel.CreateXElement();
            tabPanel.WriteXml(tabPanelElement);
            element.Add(tabPanelElement);
        }
    }

    public override void ReadXml(XElement element)
    {
        base.ReadXml(element);

        ActiveTabIndex = GetXmlAttributeValue<int>(element, "active-tab-index");

        TabPanels.Clear();

        foreach (var tabPanelElement in element.Elements())
        {
            var elementName = tabPanelElement.Name.LocalName;
            if (elementName == "tab" || elementName == "htab" || elementName == "vtab")
            {
                var tabPanel = new TabPanel(Form, this);
                tabPanel.ReadXml(tabPanelElement);
                tabPanel.Direction = elementName switch
                {
                    "htab" => FlowDirection.Horizontal,
                    "vtab" => FlowDirection.Vertical,
                    _ => null,
                };
                TabPanels.Add(tabPanel);
            }
        }
    }

    public override XElement CreateXElement()
    {
        return new XElement("tabs");
    }
}
